package com.xc.file.service.impl;

import com.xc.file.config.Constants;
import com.xc.file.config.FolderConfig;
import com.xc.file.enums.FailCode;
import com.xc.file.enums.FileSuffix;
import com.xc.file.model.DownloadModel;
import com.xc.file.service.DownloadService;
import com.xc.file.service.FileService;
import com.xc.tool.http.FileType;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>下载服务实现</p>
 *
 * @author xc
 * @version v1.0.0
 */
@Service
public class DownloadServiceImpl implements DownloadService {
    @Autowired
    private Constants constants;
    @Autowired
    private FileService fileService;

    @Override
    public String getFilePath(String hashCode) {
        List<FolderConfig> folderPath = constants.getFolderPaths();
        String filePath = null;
        for (FolderConfig folderConfig : folderPath) {
            String path = folderConfig.getPath() + File.separator + hashCode + FileSuffix.SUCCESS.getSuffix();
            File file = new File(path);
            if (file.exists()) {
                filePath = path;
            }
        }
        return filePath;
    }

    @Override
    public void downloadFile(HttpServletResponse response, DownloadModel downloadModel, Integer w, Integer h, Double s) {
        // 获取文件地址
        String filePath = getFilePath(downloadModel.getHashCode());
        if (filePath == null) {
            throw FailCode.DOWNLOAD_FILE_NOT_EXIST.getOperateException();
        }
        //是否压缩文件
        File file = new File(filePath);
        if ((w != null && h != null) || s != null) {
            String path = compressImage(file, downloadModel.getHashCode(), w, h, s);
            download(response, new File(path), downloadModel);
        } else {
            download(response, new File(filePath), downloadModel);
        }
    }

    @Override
    public void download(HttpServletResponse response, File file, DownloadModel downloadModel) {
        String range = downloadModel.getRange();
        String fileName = downloadModel.getName();
        int open = downloadModel.getOpen();
        // 清空response
        response.reset();
        String rangBytes;
        long startIndex = 0; //下载开始的字节数
        long endIndex = 0; //下载结束的字节数
        long fileLength; //文件的字节数
        // 判断是不是分段上传
        if (range != null && range.trim().length() > 0) {
            rangBytes = range.replaceAll("bytes=", "");
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            // 判断最后是不是 -
            if (rangBytes.endsWith("-")) {
                //结尾是-,最后一次下载
                startIndex = Long.parseLong(rangBytes.substring(0, rangBytes.indexOf("-")));
                fileLength = file.length() - startIndex;
                String contentRange = "bytes " + startIndex + "-" + (file.length() - 1) + "/" + file.length();
                response.setHeader("Content-Range", contentRange);
            } else { // 结尾不是-
                startIndex = Long.parseLong(rangBytes.substring(0, rangBytes.indexOf("-")));
                endIndex = Long.parseLong(rangBytes.substring(rangBytes.indexOf("-") + 1));
                fileLength = (endIndex + 1) - startIndex;
                String contentRange = range.replace("=", " ") + "/" + file.length();
                response.setHeader("Content-Range", contentRange);
            }
        } else {
            //不是分段上传
            fileLength = file.length();
            String contentRange = "bytes " + "0-" + (fileLength - 1) + "/" + fileLength;
            response.setHeader("Content-Range", contentRange);
            // 下载成功,可计算下载结果
            fileService.downloadFinish(downloadModel, fileLength);
        }
        // 获取文件类型
        String suffix = "";
        if (fileName.lastIndexOf(".") != -1) {
            suffix = fileName.substring(fileName.lastIndexOf("."));
        }
        response.setHeader("Content-Length", Long.toString(fileLength));
        //配置header
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Access-Control-Allow-Origin", "*");
        String contentType = FileType.getFileType(suffix);
        //设置文件类型
        if (contentType != null) {
            response.setContentType(contentType);
        } else {
            response.setContentType("application/octet-stream");
        }
        // 文件输出
        try (RandomAccessFile loOutput = new RandomAccessFile(file, "r")) {
            //文件是否可以直接打开
            if (open == 0) {
                response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName, "utf-8"));
            } else {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            }
            //返回的输出流
            OutputStream out = response.getOutputStream();
            //设置开始下载的位置
            loOutput.seek(startIndex);
            //创建缓存大小
            byte[] buffer = new byte[1048576]; // 1KB
            int n;
            long readLength = 0;
            //判断是否指定结束位置
            if (endIndex != 0) {
                while (readLength <= fileLength - buffer.length) {
                    n = loOutput.read(buffer);
                    readLength += n;
                    out.write(buffer, 0, n);
                }
                if (readLength <= fileLength) {
                    n = loOutput.read(buffer, 0, (int) (fileLength - readLength));
                    out.write(buffer, 0, n);
                }
            } else {
                while ((n = loOutput.read(buffer)) != -1) {
                    out.write(buffer, 0, n);
                }
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String compressImage(File file, String fileName, Integer w, Integer h, Double s) {
        String path;
        if (s != null) {
            path = constants.getTempFolder().getPath() + File.separator + s + "-" + fileName + FileSuffix.COMPRESS.getSuffix();
        } else {
            path = constants.getTempFolder().getPath() + File.separator + w + "-" + h + "-" + fileName + FileSuffix.COMPRESS.getSuffix();
        }
        File temFile = new File(path);
        // 判断文件夹是否存在
        if (!temFile.getParentFile().exists() && !temFile.getParentFile().isDirectory()) {
            if (!temFile.getParentFile().mkdirs()) {
                throw FailCode.INIT_CREATE_TEMP_FOLDER_FAIL.getOperateException();
            }
        }
        //存在返回路径
        if (temFile.exists()) {
            return path;
        }
        // 检测本地硬盘是否有足够空间
        if ((temFile.getParentFile().getFreeSpace() - constants.getTempFolder().getReserveSpace()) < temFile.length()) {
            throw FailCode.COMPRESS_FAIL_SERVER_SPACE_SHORTAGE.getOperateException();
        }
        // 生成零时文件
        try (FileOutputStream os = new FileOutputStream(temFile)) {
            if (s != null) {
                Thumbnails.of(file).scale(s).toOutputStream(os);
            } else {
                Thumbnails.of(file).size(w, h).toOutputStream(os);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }
}
